/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.ez2find.manager;

import com.ez2find.model.Area;
import com.ez2find.model.RegisterUser;
import com.ez2find.model.Service;
import com.ez2find.model.ServiceCategorie;
import com.ez2find.model.Site;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 *
 * @author Administrador
 */
@Stateless
public class ServiceManagerBean implements ServiceManagerLocal {
    
    @PersistenceContext
    private EntityManager em;
    
    public void create(Service service)throws Exception {
        em.persist(service);
    }
 
    public void update(Service service)throws Exception {
        em.merge(service);
    }

    public Service merge(Service service)throws Exception {
        return em.merge(service);
    }
        
    public void delete(Service service)throws Exception {
        service=em.merge(service);
        em.remove(service);
    }
    
    public Service find(long id){
        return em.find(Service.class,id);
    }

    public List<Service> listAll(){
        Query query=em.createNamedQuery("listAllServices");
        List<Service> result=query.getResultList();
        return result;
    }
    
    public long lastCode(){
        try{
            Query query=em.createNamedQuery("lastServiceCode");
            return (Long) query.getSingleResult();
        }catch(Exception ex){
            return 0;
        }
    }
    
    public List<Service> listServicesSite(Site site, boolean serviceC, ServiceCategorie serviceCategorie, String consult){
        Query query=em.createQuery("SELECT s FROM Service s WHERE s.site=:site AND s.status='active'"+consult+" ORDER BY s.publishDate DESC, s.code DESC");
        query.setParameter("site", site);
        if(serviceC)
            query.setParameter("serviceCategorie", serviceCategorie);
        List<Service> result=query.getResultList();
        return result;
    }
    
    public List<Service> listServicesArea(Area area, boolean serviceC, ServiceCategorie serviceCategorie, String consult){
        Query query=em.createQuery("SELECT s FROM Service s WHERE s.area=:area AND s.status='active'"+consult+" ORDER BY s.publishDate DESC, s.code DESC");
        query.setParameter("area", area);
        if(serviceC)
            query.setParameter("serviceCategorie", serviceCategorie);
        List<Service> result=query.getResultList();
        return result;
    }
    
}
